package org.yejiali.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.yejiali.annotaion.SystemLog;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Author:yejiali
 * @Date:2025/3/5-03-05-8:37
 * @Decsription:org.yejiali.aspect 切面类
 * @Version:1.0
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    //确定切点
    @Pointcut("@annotation(org.yejiali.annotaion.SystemLog)") //在切点上标注注解
    public void pt(){
    }
    @Around("pt()") //环绕通知的方法
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret;
        try {
            handlerBefore(joinPoint); //将当前被执行的方法对象传入
            ret = joinPoint.proceed();
            handleAfter(ret);
        } finally {


        }
        return ret;

    }

    private void handleAfter(Object ret) {
        // 打印出参
        log.info("Response: {}", JSON.toJSONString(ret));
        // 结束后换行
        log.info("=======End=======" + System.lineSeparator());
    }

    private void handlerBefore(ProceedingJoinPoint joinPoint) {
        //获取请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取被增强的方法上的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);



        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL  :{}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName :{}",systemLog.businessName()) ;
        // 打印 Http method
        log.info("HTTP Method    :{}",request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName() );
        // 打印请求的 IP
        log.info("IP  :{}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));

    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        // 获取方法上的 @SystemLog 注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        return systemLog;
    }

}
